# 这是所有请求的父类文件
import requests

from loguru import logger

import settings

from cacheout import Cache

cache = Cache()


class Base:
    def comb_url(self, path):
        const_url = 'http://192.168.252.117:9527'
        return const_url + path

    def get_method(self, url, search_para=None, **headers):
        try:
            if not search_para:
                res = requests.get(url, headers=headers)
                result = res.json()
            else:
                result = requests.get(url, search_para, headers=headers).json()
            logger.debug(f'请求方法：get，请求地址：{url}，响应：{result}')
            return result
        except Exception as e:
            if not search_para:
                res = requests.get(url, headers=headers)
                result = res.json()
            else:
                result = requests.get(url, search_para, headers=headers).json()
            logger.error(f'报错：{e}，响应：{result}')

    def post_method(self, url, body, **headers):
        try:
            res = requests.post(url, json=body, headers=headers)
            result = res.json()
            logger.debug(f'请求方法：post，请求地址：{url}，响应：{result}')
            return result
        except Exception as e:
            res = requests.post(url, json=body, headers=headers)
            result = res.json()
            logger.error(f'报错：{e}，响应：{result}')

    def login(self):
        login_url = self.comb_url('/admin/auth/login')
        login_result = self.post_method(login_url, settings.supremmanager_info)
        logger.info(f'响应：{login_result}')
        token = login_result.get('data').get('token')
        global cache
        cache.set('token', token)
        return login_result

    def headers(self):
        return {"Content-Type": "application/json", "X-Litemall-Admin-Token": cache.get('token')}


if __name__ == '__main__':
    test = Base()
    print(test.comb_url('/admin/auth/login'))
    print(test.login(), test.headers())
